<template>
  <div class="modal modal-blur fade" id="modal-add-plugin-label" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">新增插件标签</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="submitForm">
            <div class="mb-3">
              <label class="form-label required">标签名称</label>
              <input type="text" class="form-control" v-model="formData.name" 
                     :class="{'is-invalid': errors.name}"
                     @input="validateField('name')"
                     required>
              <div class="invalid-feedback" v-if="errors.name">
                {{ errors.name }}
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label required">标签类型</label>
              <input type="text" class="form-control" v-model="formData.labelType" 
                     :class="{'is-invalid': errors.labelType}"
                     @input="validateField('labelType')"
                     required>
              <div class="invalid-feedback" v-if="errors.labelType">
                {{ errors.labelType }}
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label">备注</label>
              <textarea class="form-control" v-model="formData.description" rows="3"></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-link link-secondary" data-bs-dismiss="modal">
            取消
          </button>
          <button type="button" class="btn btn-primary ms-auto" @click="validateAndSubmit">
            保存
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 添加提示框组件 -->
  <ComponentModal
      :modalId="'modal-success-plugin-label'"
      :title="'信息'"
      :message="modalMessage"
      :cancelText="'取消'"
      :confirmText="'确定'"
      ref="componentModalRef"
  />
</template>

<script setup>
import {ref, reactive} from 'vue';
import {Modal} from 'bootstrap';
import ComponentModal from '@/components/ComponentModal.vue';

const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;
const modal = ref(null);
const componentModalRef = ref(null);
const modalMessage = ref('');

const formData = reactive({
  name: '',
  description: '',
  labelType: ''
});

const errors = reactive({
  name: '',
  labelType: ''
});

const validateField = (field) => {
  errors[field] = '';
  if (field === 'name') {
    if (!formData.name) {
      errors.name = '请输入标签名称';
    } else if (formData.name.length > 50) {
      errors.name = '标签名称不能超过50个字符';
    }
  } else if (field === 'labelType') {
    if (!formData.labelType) {
      errors.labelType = '请输入标签类型';
    } else if (formData.labelType.length > 50) {
      errors.labelType = '标签类型不能超过50个字符';
    }
  }
};

const validateForm = () => {
  validateField('name');
  validateField('labelType');
  return !errors.name && !errors.labelType;
};

const openModal = () => {
  if (!modal.value) {
    modal.value = new Modal(document.getElementById('modal-add-plugin-label'));
  }
  // 重置表单和错误信息
  formData.name = '';
  formData.description = '';
  formData.labelType = '';
  errors.name = '';
  errors.labelType = '';
  modal.value.show();
};

const validateAndSubmit = async () => {
  if (validateForm()) {
    await submitForm();
  }
};

const submitForm = async () => {
  try {
    const formDataToSend = new URLSearchParams();
    formDataToSend.append('name', formData.name);
    formDataToSend.append('remark', formData.description);
    formDataToSend.append('labelType', formData.labelType);

    const response = await fetch(`${apiBaseUrl}/resident/plugin-label/add`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: formDataToSend
    });
    const data = await response.json();
    if (data.success) {
      modal.value.hide();
      // 重置表单
      formData.name = '';
      formData.description = '';
      formData.labelType = '';
      // 触发父组件的刷新
      window.dispatchEvent(new CustomEvent('plugin-label-added'));
    } else {
      // 显示后端返回的错误信息
      modalMessage.value = data.errorMsg || '保存失败，请重试';
      componentModalRef.value.openWarnModal(modalMessage.value);
    }
  } catch (error) {
    console.error('Error submitting form:', error);
    modalMessage.value = '保存失败，请重试';
    componentModalRef.value.openWarnModal(modalMessage.value);
  }
};

defineExpose({
  openModal
});
</script>

<style scoped>
.required:after {
  content: " *";
  color: red;
}
</style> 